package br.com.rodolfo.timesheet.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.rodolfo.timesheet.entity.Pessoa;




@Repository("pessoaDAO")
public class PessoaDAO {
	
	@PersistenceContext
	protected EntityManager entityManager;

	@Transactional(readOnly=true)
	public List<Pessoa> findAll() 
			throws Exception{
		String sQuery = "Select p from Pessoa p";
		Query q = entityManager.createQuery(sQuery);
		@SuppressWarnings("unchecked")
		List<Pessoa> list = (List<Pessoa>) q.getResultList();
		return list;
	}
	
	@Transactional(readOnly=true)
	public Pessoa findByCpf(Long cpf)
		throws Exception{
		String sQuery = "Select p from Pessoa p where p.cpf = :codigo";
		Query q = entityManager.createQuery(sQuery);
		q.setParameter("codigo", cpf);
		return (Pessoa) q.getSingleResult();
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true)
	public List<Pessoa> findByProp(HashMap<String, String> param)
			throws Exception{
		if (param.isEmpty()){
			return findAll();
		}
		StringBuilder sQuery = new StringBuilder("Select p from Pessoa where 1=1 ");
		 for (Entry<String, String> entry : param.entrySet()) {
			 sQuery.append(" and ");
			 sQuery.append(entry.getKey());
			 sQuery.append(" = ");
			 sQuery.append(entry.getValue());
		 }
		Query q = entityManager.createQuery(sQuery.toString());
		return (List<Pessoa>) q.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true)
	public List<Pessoa> findByNome(Long nome)
		throws Exception{
		String sQuery = "Select p from Pessoa p where p.nome like '%:nome%' order by p.nome";
		Query q = entityManager.createQuery(sQuery);
		q.setParameter("nome", nome);
		return (List<Pessoa>) q.getResultList();
	}
	
	@Transactional
	public Pessoa create(Pessoa p)
		throws Exception{
		entityManager.persist(p);
		return p;
	}
	@Transactional
	public void update(Pessoa p)
		throws Exception{
		entityManager.merge(p);		
	}
	
	@Transactional
	public void delete(Pessoa p)
		throws Exception{
		p = entityManager.find(Pessoa.class, p.getId());
		entityManager.remove(p);
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	
	

}
